export function isMarkdown(text) {
    // 检查文本中是否包含Markdown常见的标记
    const markdownPatterns = [
        /\*\*\*(.*?)\*\*\*/g, // 粗体
        /__([^_]+)__/g, // 下划线
        /```(.*?)```/g, // 代码块
        /\[(.*?)\]\((.*?)\)/g, // 超链接
        /# (.*)/g, // 标题
        /\n\n(.*)\n\n/g // 段落
    ];

    return markdownPatterns.some(pattern => pattern.test(text));
}


export function containsMarkdownCode(text) {
  const codeBlockPattern = /```[\s\S]*?```|`[^`]*`/g;
  return codeBlockPattern.test(text);
}

// const text = "Here is some text with an inline code `var x = 10;` and a code block ```function example() { return 'Hello, World!'; }```";
// console.log(containsMarkdownCode(text)); // 输出: true


export function markdownHeadersToMenuArray(markdown) {
    // 使用正则表达式匹配Markdown标题
    const headerRegex = /^#{1,6} (.*)/gm;
    let match;
    const menuArray = [];

    // 循环匹配所有标题
    while ((match = headerRegex.exec(markdown)) !== null) {
        // match[0] 是整个匹配的字符串，例如 "# 一级标题"
        // match[1] 是匹配的标题文本，例如 "一级标题"
        const level = match[0].startsWith('#') ? match[0].match(/#/g).length : 0;
        const text = match[1].trim();

        // 将标题信息添加到数组
        menuArray.push({
            level: level,
            text: text
        });
    }

    return menuArray;
}

export function createHtmlMenuFromArray(menuArray) {
    return menuArray.map(item => `<li class="level-${item.level}">${item.text}</li>`).join('');
}



function copyToClipboard(content) {
    if (window.clipboardData) {
        window.clipboardData.setData('text', content);
    } else {
        (function (content) {
            document.oncopy = function (e) {
                e.clipboardData.setData('text', content);
                e.preventDefault();
                document.oncopy = null;
            }
        })(content);
        document.execCommand('Copy');
    }
}

export function initCopyBtn() {
    [...document.getElementsByTagName("pre")].forEach(item => {
            item.style.position = "relative";
            let copyButton = document.createElement("button")
            copyButton.style.cssText = 'border-radius: 4px;position:absolute;right:10px;top:10px;cursor: pointer'
            copyButton.innerHTML = "复制";
            copyButton.onclick = function () {
                let copyData = item.firstChild.innerText
                copyToClipboard(copyData)
                copyButton.innerHTML = "复制成功";
                setTimeout(function() {
                    copyButton.innerHTML = "复制";
                }, 1000);
            }
            item.appendChild(copyButton)
    });
}